//
//  HYMDatePicker.m
//  HYMDatePicker
//
//  Created by wmm on 15/11/5.
//  Copyright © 2015年 hanen. All rights reserved.
//

#import "HYMDatePicker.h"
#import "Macro.h"

@interface HYMDatePicker ()<UIPickerViewDataSource,UIPickerViewDelegate>
{
    NSDate *today;
    NSCalendar *calendar;
    NSString *Month2Str;
    int yearCount;
    BOOL isToday;
    int TodaymonthD;
}
//pickerView数据源
@property (strong, nonatomic) NSArray *dataSourceForYearComponent;
@property (strong, nonatomic) NSArray *dataSourceForMonthComponent;
@property (strong, nonatomic) NSArray *dataSourceForDayComponent;

@property (assign, nonatomic) int yearD;
@property (assign, nonatomic) int monthD;
@property (assign, nonatomic) int dayD;

@end

@implementation HYMDatePicker


- (instancetype)init{
    self = [super init];
    if(self){
        yearCount = CHOOSE_YEAR_COUNT-1;
        today = [NSDate date];
        calendar = [NSCalendar currentCalendar];
        isToday = YES;
        
        NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
        NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:today];
        int year = (int)[dateComponent year];
        int month = (int)[dateComponent month];
        int day = (int)[dateComponent day];
        _yearD = year;
        _monthD = month;
        TodaymonthD = month;
        _dayD = day;
        
        self.dataSource = self;
        self.delegate = self;
    }
    return self;
}

#pragma mark - 初始化
- (NSArray *)dataSourceForYearComponent{
    
    NSUInteger unitFlags = NSYearCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:today];
    int Year = (int)[dateComponent year];
    
    if(!_dataSourceForYearComponent){
        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 0; i < CHOOSE_YEAR_COUNT; i++) {
            int year = Year-yearCount+i;
            NSMutableString *dateStr = [NSMutableString stringWithFormat:@"%d年",year];
            [arr addObject:dateStr];
        }
        _dataSourceForYearComponent = [arr copy];
    }
    return _dataSourceForYearComponent;
}
- (NSArray *)dataSourceForMonthComponent{
    if(!_dataSourceForMonthComponent){
        [self DateOfMonth];
    }
    return _dataSourceForMonthComponent;
}
- (NSArray *)dataSourceForDayComponent{
    if(!_dataSourceForDayComponent){
        [self DateOfDay];
    }
    return _dataSourceForDayComponent;
}

#pragma mark - UIPickerViewDataSource,UIPickerViewDelegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    switch (component) {
        case 0:
            return self.dataSourceForYearComponent.count;
            break;
        case 1:
            return self.dataSourceForMonthComponent.count;
            break;
        case 2:
            return self.dataSourceForDayComponent.count==0?0:self.dataSourceForDayComponent.count;
            break;
        default:
            return 0;
            break;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
    int Year2 = (int)[dateComponent year];
    int Month2 = (int)[dateComponent month];
    
    if (component == 0) {
        _yearD = (int)row+Year2-yearCount;
    }
    if (component == 1) {
        _monthD = (int)row+1;
    }
    if (component == 2) {
        _dayD = (int)row+1;
    }
    
    yearStr = [NSString stringWithFormat:@"%d",_yearD];
    
    if (_monthD >=10) {
        monthStr = [NSString stringWithFormat:@"%d",_monthD];
    }else if (_monthD < 10){
        monthStr = [NSString stringWithFormat:@"0%d",_monthD];
    }
    
    if (_dayD >=10) {
        dayStr = [NSString stringWithFormat:@"%d",_dayD];
    }else if (_dayD <10){
        dayStr = [NSString stringWithFormat:@"0%d",_dayD];
    }
    
    NSString *dateStr = [NSString stringWithFormat:@"%@%@01",yearStr,monthStr];
    
    NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
    
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh"]];
    
    [inputFormatter setDateFormat:@"yyyyMMdd"];
    
    NSDate*inputDate = [inputFormatter dateFromString:dateStr];
    
    if (Month2 < 10) {
        Month2Str = [NSString stringWithFormat:@"0%d",Month2];
    }
    else{
        Month2Str = [NSString stringWithFormat:@"%d",Month2];
    }
    
    if (_yearD == Year2) {
        isToday = YES;
        [self DateOfMonth];
         if (_monthD > Month2||_monthD == Month2) {
            today = [NSDate date];
            [self DateOfDay];
             _monthD = Month2;
             if (_monthD >=10) {
                 monthStr = [NSString stringWithFormat:@"%d",_monthD];
             }else if (_monthD < 10){
                 monthStr = [NSString stringWithFormat:@"0%d",_monthD];
             }
         }
         else{
             today = inputDate;
             [self otherDateOfDate];
         }
    }else{
        isToday = NO;
        [self DateOfOtherMonth];
        today = inputDate;
        [self otherDateOfDate];
    }

    //刷新 每月的天数
    [self reloadComponent:2];
    [self reloadComponent:1];
    
    int day = (int)[dateComponent day];
        if ([dayStr intValue] > day) {
            if (day >=10) {
                dayStr = [NSString stringWithFormat:@"%d",day];
            }else if (day <10){
                dayStr = [NSString stringWithFormat:@"0%d",day];
            }
        }
    
    if(self.delegateDiy && [self.delegateDiy respondsToSelector:@selector(currentSelectedDate: month: day:)]){
        [self.delegateDiy currentSelectedDate:yearStr month:monthStr day:dayStr];
    }
    NSLog(@"------------============  ***   %@ %@ %@",yearStr,monthStr,dayStr);
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    switch (component) {
        case 0:
            return [UIScreen mainScreen].bounds.size.width*0.22;
            break;
        case 1:
            return [UIScreen mainScreen].bounds.size.width*0.22;
            break;
        case 2:
            return [UIScreen mainScreen].bounds.size.width*0.33;
            break;
        default:
            return [UIScreen mainScreen].bounds.size.width*0.25;
            break;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view

{
    UILabel *myView = nil;
    
    myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 100, 30)];
    
    myView.textAlignment = NSTextAlignmentCenter;
    
    if ( kScreenWidth > 320 && kScreenWidth <375) {
        myView.font = [UIFont systemFontOfSize:14];
    }else if (kScreenWidth > 375 && kScreenWidth <414)
    {
        myView.font = [UIFont systemFontOfSize:16];
    }else{
        myView.font = [UIFont systemFontOfSize:18];
    }
    myView.backgroundColor = [UIColor clearColor];
    
    if (component == 0) {
        myView.text = [_dataSourceForYearComponent objectAtIndex:row];
    }
    else if (component == 1){
        myView.text = [_dataSourceForMonthComponent objectAtIndex:row];
    }else if (component == 2){
        myView.text = [_dataSourceForDayComponent objectAtIndex:row];
    }
    return myView;
    
}

- (void)DateOfMonth
{
    int any;
    if (isToday == YES) {
        any  = TodaymonthD;
    }else{
        any = _monthD;
    }
    
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 12; i++) {
            if (i < any) {
                int month = 1+i;
                NSMutableString *dateStr = [NSMutableString stringWithFormat:@"%d月",month];
                [arr addObject:dateStr];
            }
    }
    _dataSourceForMonthComponent = [arr copy];
    
}

- (void)DateOfOtherMonth
{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 12; i++) {
            int month = 1+i;
            NSMutableString *dateStr = [NSMutableString stringWithFormat:@"%d月",month];
            [arr addObject:dateStr];
        
    }
    _dataSourceForMonthComponent = [arr copy];
    
}

- (void)DateOfDay
{
    //获取当月的天数
    NSRange days = [calendar rangeOfUnit:NSDayCalendarUnit
                                  inUnit:NSMonthCalendarUnit
                                 forDate:today];
    
    NSMutableArray *arr = [NSMutableArray array];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"zh_CN"]];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *str = [NSString stringWithFormat:@"%@ 00:00:00",[formatter stringFromDate:[NSDate date]]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *baseDate = [formatter dateFromString:str];
    
    NSUInteger unitFlags = NSDayCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:today];
    int day = (int)[dateComponent day];
    
    for (NSInteger i = 0; i < days.length; i++) {
        
        if(i < day-1){
            NSDate *date = [NSDate dateWithTimeInterval:24*60*60*-(day-1-i) sinceDate:baseDate];
            [formatter setDateFormat:@"dd日EE"];
            NSMutableString *dateStr = [[formatter stringFromDate:date] mutableCopy];
            [arr addObject:dateStr];
        }
        else if(i == day-1){
            [arr addObject:@"今天"];
        }
        else if(i > day-1){
            NSDate *date = [NSDate dateWithTimeInterval:24*60*60*(i-day+1) sinceDate:baseDate];
            [formatter setDateFormat:@"dd日EE"];
            NSMutableString *dateStr = [[formatter stringFromDate:date] mutableCopy];
//            [arr addObject:dateStr];
        }
    }
    _dataSourceForDayComponent = [arr copy];
    
}

- (void)otherDateOfDate
{
    NSRange days = [calendar rangeOfUnit:NSDayCalendarUnit
                                  inUnit:NSMonthCalendarUnit
                                 forDate:today];
    
    NSMutableArray *arr = [NSMutableArray array];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"zh_CN"]];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *str = [NSString stringWithFormat:@"%@ 00:00:00",[formatter stringFromDate:today]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *baseDate = [formatter dateFromString:str];
    
    NSUInteger unitFlags = NSDayCalendarUnit;
    NSDateComponents *dateComponent2 = [calendar components:unitFlags fromDate:today];
    int day = (int)[dateComponent2 day];
    
    for (NSInteger i = 0; i < days.length; i++) {
        
        NSDate *date = [NSDate dateWithTimeInterval:24*60*60*day*i sinceDate:baseDate];
        [formatter setDateFormat:@"dd日EE"];
        NSMutableString *dateStr = [[formatter stringFromDate:date] mutableCopy];
        [arr addObject:dateStr];
    }
    _dataSourceForDayComponent = [arr copy];
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
